<template>
  <div>
    <el-page-header @back="goBack" content="课件">
    </el-page-header>
<!--    <el-row style="margin-top: 10px;">-->
<!--      <el-col :span="20">-->
<!--        <div>-->
<!--          <el-button type="primary" @click="dialogFormVisible = true">添加课件</el-button>-->
<!--        </div>-->
<!--      </el-col>-->
<!--      <el-col :span="4">-->
<!--        <div style="text-align: right">-->
<!--          <el-input placeholder="请输入课件名称" v-model="activityContentSearch" class="input-with-select">-->
<!--            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>-->
<!--          </el-input>-->
<!--        </div>-->
<!--      </el-col>-->
<!--    </el-row>-->
    <div style="margin-top: 10px;">
      <div style="text-align: right;width: 300px;">
        <el-input placeholder="请输入课件名称" v-model="activityContentSearch" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
        </el-input>
      </div>
    </div>
    <div style="margin-top: 10px;">
      <el-table :data="activityContentList" style="width: 100%" border :empty-text="loadingFlag === true ? '正在拼命加载中...':'暂无数据'">
        <el-table-column prop="contentName" label="课件名称"></el-table-column>
        <el-table-column prop="contentLevel" label="课件等级">
          <template slot-scope="scope">
            <span v-if="scope.row.contentLevel === 1">初级</span>
            <span v-else-if="scope.row.contentLevel === 2">中级</span>
            <span v-else>高级</span>
          </template>
        </el-table-column>
        <el-table-column prop="contentType" label="课件类型">
          <template slot-scope="scope">
            <span v-if="scope.row.contentType === 1">图片</span>
            <span v-else-if="scope.row.contentType === 2">视频</span>
            <span v-else>PDF</span>
          </template>
        </el-table-column>
        <el-table-column prop="mediaView.mediaUrl" label="课件地址" width="500px">
          <template slot-scope="scope">
            <span>{{ mediaHost + scope.row.mediaView.mediaUrl }}</span>
          </template>
        </el-table-column>
        <el-table-column align="right">
          <template slot-scope="scope">
            <el-button
              size="mini">
              <el-link :underline="false" target="_blank" :href="mediaHost + scope.row.mediaView.mediaUrl">查 看</el-link>
            </el-button>
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="danger"-->
<!--              @click="canDeleteActivityContent(scope.$index, scope.row)">删 除-->
<!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <!--请求标识-->
      <div v-if="loadingFlag=== true" style="text-align: center;font-size: larger;margin-top: 10px;">
        <i  class="el-icon-loading"></i>
      </div>
      <div v-else-if="activityContentPage.hasMore === true" style="text-align: center;font-size: small;color: #99a9bf;margin-top: 10px;" @click="loadingMore()">
        <span>--点击加载更多--</span>
      </div>
      <div v-else-if="activityContentList.length > 0" style="text-align: center;font-size: small;color: #99a9bf;margin-top: 10px;">
        <span>--没有更多数据了--</span>
      </div>
    </div>
    <!--创建课件-->
    <el-dialog title="添加课件" :visible.sync="dialogFormVisible" width="30%" :before-close="closeDialog"
               :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="activityContent">
        <el-form-item label="课件名称">
          <el-input type="text" placeholder="请输入课件名称" v-model="activityContent.contentName" autocomplete="off"
                    maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="课件等级">
          <el-radio-group v-model="activityContent.contentLevel">
            <el-radio label="1">初级</el-radio>
            <el-radio label="2">中级</el-radio>
            <el-radio label="3">高级</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课件类型">
          <el-radio-group v-model="activityContent.contentType"  @change="changeContentType">
            <el-radio label="2">视频</el-radio>
            <el-radio label="3">PDF</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div>
        <label for="fileInput">
          <el-image v-show="activityContent.contentType === '2'" fit="cover"
                    :src="this.$global.mediaHost + this.$global.mp4Image"
                    style="height: 36px; width: 36px;">
          </el-image>
          <el-image v-show="activityContent.contentType === '3'" fit="cover"
                    :src="this.$global.mediaHost + this.$global.pdfImage"
                    style="height: 36px; width: 36px;">
          </el-image>
        </label>
        <input v-show="false" type="file" id="fileInput" :accept="activityContentType" @change="uploadActivityContent">
        <el-progress v-show="showPercentage === true && percentageNum <100" :percentage="percentageNum"></el-progress>
        <el-progress v-show="showPercentage === true && percentageNum >= 100" :percentage="100" status="success"></el-progress>
        <div v-show="activityContent.contentType !== ''">{{ fileName }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="saveActivityContent()">确 认</el-button>
      </div>
    </el-dialog>

    <!--删除提示框-->
    <el-dialog title="提示" :visible.sync="deleteDialogVisible" width="20%">
      <span>确认删除此课件吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteActivityContent()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ActivityContent",
  data() {
    return {
      mediaHost: this.$global.mediaHost,
      activityId: this.$route.query.activityId,
      activityContentList: [],
      activityContentPage: this.$global.indexPage,
      paramsData: {
        activityId: '',
        page: {}
      },
      activityContent: {
        contentLevel: '',
        contentName: '',
        contentType: '',
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      loadingFlag: false,
      activityContentSearch: '',
      fileName: '点击图标上传文件',
      formLabelWidth: '80px',
      activityContentId: '',
      activityContentUrl:'',
      activityContentType: this.$global.videoType + "/*",
      showPercentage: false,
      percentageNum:0,
      abortActivityContentUrl:'',
      uploadId:''
    }
  },
  mounted() {
    addEventListener('scroll', this.handleScroll)//监听函数
  },
  methods: {
    handleScroll() {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      //变量windowHeight是可视区的高度
      let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      //变量scrollHeight是滚动条的总高度
      let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      //滚动条到底部的条件
      if (scrollTop + windowHeight === scrollHeight) {
        //你想做的事情
        if (this.activityContentPage.hasMore === true && !this.loadingFlag) {
          this.activityContentPage.page += 1;
          this.getActivityContentList();
        }
      }
    },
    loadingMore:function () {
      this.activityContentPage.page += 1;
      this.getActivityContentList();
    },
    goBack() {
      this.$router.push({path: "/homePage/activity"})
    },
    /**
     *获得课件列表
     *
     */
    getActivityContentList: function () {
      this.loadingFlag = true;
      this.paramsData.activityId = this.activityId
      this.paramsData.page = this.activityContentPage
      this.paramsData.activityContentSearch = this.activityContentSearch
      this.$ajax({
        method: 'post',
        headers: this.$global.headers,
        url: this.$global.host + '/v1/activity/content/activityContentList',
        data: JSON.stringify({
          "data": this.paramsData,
          "user": this.$global.getUser(),
          "teamId": this.$global.getTeamId()
        }),
      }).then(response => {
        const responseData = response.data.data;
        const responseState = response.data.state
        if (2000 === responseState.code) {
          this.loadingFlag = false;
          this.activityContentList = this.activityContentList.concat(responseData.pageData.data)
          this.activityContentPage = responseData.pageData.page
        } else {
          this.$message.error({
            message: responseState.msg,
            center: true,
            duration: 1000
          });
        }
      }).catch(function (err) {
        console.log(err)
      })
    },
    /**
     * 查找
     */
    search: function () {
      this.activityContentPage = this.$global.indexPage
      this.activityContentList = []
      this.getActivityContentList()
    },
    /**
     * 保存课件
     */
    saveActivityContent() {
      if (this.checkInput()) {
        this.dialogFormVisible = false
        this.paramsData.activityId = this.activityId
        this.paramsData.activityContentUrl = this.activityContentUrl
        this.paramsData.contentLevel = this.activityContent.contentLevel
        this.paramsData.contentType = this.activityContent.contentType
        this.paramsData.contentName = this.activityContent.contentName
        this.$ajax({
          method: 'post',
          headers: this.$global.headers,
          url: this.$global.host + '/v1/activity/content/saveActivityContent',
          data: JSON.stringify({
            "data": this.paramsData,
            "user": this.$global.getUser(),
            "teamId": this.$global.getTeamId()
          }),
        }).then(response => {
          const responseData = response.data.data;
          const responseState = response.data.state
          if (2000 === responseState.code) {
            this.$message.success({
              message: "添加课件成功",
              center: true,
              duration: 1000
            });
            this.deleteData()
            this.closeDialogDeleteData()
            this.getActivityContentList()
          } else {
            this.$message.error({
              message: responseState.msg,
              center: true,
              duration: 1000
            });
          }
        }).catch(function (err) {
          console.log(err)
        })
      }
    },
    /**
     * 上传课件内容到云端
     *
     */
    uploadActivityContent: function (e) {
      if (e.target.files[0] !== undefined) {
        let fileName = e.target.files[0].name;
        let fileType = e.target.files[0].type;
        let mediaType = ""
        if (this.activityContent.contentType === '2') {
          mediaType = this.$global.videoType
          if (!fileType.includes(this.$global.videoType)) {
            this.$message.warning({
              message: "文件类型错误",
              center: true,
              duration: 1000
            });
            return false;
          }
        } else if (this.activityContent.contentType === '3'){
          mediaType = this.$global.pdfType
          if (!fileType.includes(this.$global.pdfType)) {
            this.$message.warning({
              message: "文件类型错误",
              center: true,
              duration: 1000
            });
            return false;
          }
        }
        this.fileName = fileName
        fileName = "/"+ mediaType +"/" + this.$global.randomStr(24) + fileName.substring(fileName.lastIndexOf("."))
        this.abortActivityContentUrl = fileName
        const OSS = require('ali-oss')
        const client = new OSS({
          bucket: this.$global.bucket,
          region: this.$global.region,
          secure: true,
          accessKeyId: this.$global.accessKeyId,
          accessKeySecret: this.$global.accessKeySecret,
        });
        const progress = (p, _checkpoint) => {
          //console.log(p * 100); // Object的上传进度。
          //console.log(_checkpoint); // 分片上传的断点信息。
          this.percentageNum = parseInt(p * 100 + "")
          this.uploadId = _checkpoint.uploadId
        };
        const asyncThis = this
        // 开始分片上传。
        async function multipartUpload() {
          asyncThis.showPercentage = true
          try {
            // object-name可以定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至Bucket根目录或Bucket下的指定目录。
            const result = await client.multipartUpload(fileName, e.target.files[0], {
              progress,
            });
            asyncThis.activityContentUrl = fileName;
            asyncThis.uploadId = ''
          } catch (e) {
            if (e.code === 'ConnectionTimeoutError') {
              console.log('TimeoutError');
              asyncThis.$message.warning({
                message: "上传文件超时",
                center: true,
                duration: 1000
              });
            }
            asyncThis.uploadId = ''
            asyncThis.percentageNum = 0
            console.log(e);
          }
        }
        multipartUpload();
      }
    },
    abortUpdateActivityContent:function() {
      const OSS = require('ali-oss')
      const client = new OSS({
        bucket: this.$global.bucket,
        region: this.$global.region,
        secure: true,
        accessKeyId: this.$global.accessKeyId,
        accessKeySecret: this.$global.accessKeySecret,
      });
      const asyncThis = this
      async function abortMultipartUpload() {
        const name = asyncThis.abortActivityContentUrl; // Object所在Bucket的完整路径。
        const uploadId = asyncThis.uploadId; // 分片上传uploadId。
        const result = await client.abortMultipartUpload(name, uploadId);
        asyncThis.uploadId = ''
        asyncThis.percentageNum = 0
        //console.log(result);
      }
      abortMultipartUpload();
    },
    /**
     *确认删除课件
     */
    canDeleteActivityContent: function (index, row) {
      this.deleteDialogVisible = true
      this.activityContentId = row.activityContentId
    },
    /**
     * 删除课件
     *
     * @param index
     * @param row
     */
    deleteActivityContent: function () {
      this.deleteDialogVisible = false
      this.paramsData.activityContentId = this.activityContentId
      this.$ajax({
        method: 'post',
        headers: this.$global.headers,
        url: this.$global.host + '/v1/activity/content/deleteActivityContent',
        data: JSON.stringify({
          "data": this.paramsData,
          "user": this.$global.getUser(),
          "teamId": this.$global.getTeamId()
        }),
      }).then(response => {
        const responseData = response.data.data;
        const responseState = response.data.state
        if (2000 === responseState.code) {
          this.$message.success({
            message: '删除课件成功',
            center: true,
            duration: 1000
          });
          this.deleteData()
          this.getActivityContentList()
        } else {
          this.$message.error({
            message: responseState.msg,
            center: true,
            duration: 1000
          });
        }
      }).catch(function (err) {
        console.log(err)
      })
    },
    cancel: function () {
      this.dialogFormVisible = false
      this.closeDialogDeleteData()
    },
    closeDialog: function (done) {
      this.closeDialogDeleteData()
      done();
    },
    deleteData: function () {
      this.activityContentPage = this.$global.indexPage
      this.activityContentList = []
    },
    closeDialogDeleteData: function () {
      this.activityContent.contentLevel = ''
      this.activityContent.contentName = ''
      this.activityContent.contentType = ''
      this.fileName = '点击图标上传文件'
      this.activityContentUrl = ''
      this.activityContentSearch = ''
      if (this.uploadId !== '') {
        this.abortUpdateActivityContent()
      }
      this.showPercentage = false
      this.percentageNum = 0
    },
    changeContentType:function () {
      this.fileName = '点击图标上传文件'
      this.activityContentUrl = ''
      if (this.activityContent.contentType === '2') {
        this.activityContentType = this.$global.videoType + "/*"
      } else if (this.activityContent.contentType === '3') {
        this.activityContentType = "application/" + this.$global.pdfType
      }
      if (this.uploadId !== '') {
        this.abortUpdateActivityContent()
      }
      this.showPercentage = false
      this.percentageNum = 0
    },
    checkInput:function () {
      if (this.showPercentage === true && this.percentageNum < 100) {
        this.$message.warning({
          message: "文件正在上传中，请再耐心等待",
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityContent.contentName === '') {
        this.$message.warning({
          message: "请输入课件名称",
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityContent.contentName.length > 50) {
        this.$message.warning({
          message: "课件名称太长了，请调整一下",
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityContent.contentLevel === '') {
        this.$message.warning({
          message: "请选择课件等级",
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityContent.contentType === '') {
        this.$message.warning({
          message: "请选择课件类型",
          center: true,
          duration: 1000
        });
        return false
      }
      if (this.activityContentUrl === '') {
        this.$message.warning({
          message: "请选择上传的课件文件",
          center: true,
          duration: 1000
        });
        return false
      }
      return true
    }
  },
  created() {
    this.getActivityContentList()
  }
}
</script>

<style scoped>

</style>
